<?php

class RM_User_eWAYpaymentsController extends RM_Controller {

    /**
     * Presnets the CC form
     */
    public function formAction() {
        for ($i = 1; $i <= 12; $i++) {
            $months[$i]['value'] = $i;
            if (strlen($i) == 1) {
                $text = "0" . $i;
            } else {
                $text = $i;
            }
            $months[$i]['text'] = $text;
        }

        $count = 0;
        $yearnow = (int) date("Y");
        for ($i = $yearnow; $i <= $yearnow + 10; $i++) {
            $expiry_years[$count]['value'] = $i;
            $expiry_years[$count]['text'] = $i;
            $count+=1;
        }
        $this->view->months = $months;
        $this->view->year_expire = $expiry_years;

        $model = new RM_eWAYpayments;
        $settings = $model->getSettings()->current();
        $this->view->settings = $settings;
    }

    /**
     * The ajax controller for processing the form details in real time.
     */
    public function processJsonAction() {

        RM_Log::toLog("*** eWay Payments: Controller processJsonAction Started ***");

        $x_card_num = $this->_getParam('x_card_num');
        $cc_expire_date_month = $this->_getParam('cc_expire_date_month');
        $cc_expire_date_year = $this->_getParam('cc_expire_date_year');
        $x_card_code = $this->_getParam('x_card_code');

        $valid = new Zend_Validate_CreditCard();
        if ($valid->isValid($x_card_num)) {

            RM_Log::toLog("eWay Payments: Card Passed Validation");

            // card valid
            $reservationDetails = RM_Reservation_Manager::getInstance()->getAllDetails();
            $reservationsModel = new RM_Reservations();
            $unitModel = new RM_Units;
            $lang = RM_Environment::getInstance()->getLocale();

            //$chargetotal = 0;
            $bookingref = RM_Reservation_Manager::getInstance()->getReservationID();
            // create the description text
            $description = $bookingref . ": ";
            $count = 1;
            foreach ($reservationDetails as $details) {

                //$chargetotal = $chargetotal + $details->getTotal(); // get the total
                $unit = $details->getUnit();
                $period = $details->getPeriod();
                $unit_details = $unitModel->get($unit->getId(), $lang);
                $description .= $this->_translate->_('Admin.PayPal.Main', 'Selection') . " " . $count . "(" . $unit_details->name . " (" . $unit->getId() . ") " . $period->getStart() . " " . $this->_translate->_('Admin.PayPal.Main', 'to') . " " . $period->getEnd() . ")";
                $count+=1;
            }

            $model = new RM_eWAYpayments;
            $settings = $model->getSettings()->current();

            if ($settings->overridetotal > 0){
                $chargetotal = $settings->overridetotal;
            } else {
                $chargetotal = $reservationsModel->find($bookingref)->current()->getTotalPrice();
                $chargetotal = $chargetotal; 
            }

            $userdetails = RM_Reservation_Manager::getInstance()->getUser()->toArray();
            $reservationPostdata = $reservationsModel->find($bookingref)->current();

            // gather the userdetails
            $userData['first_name'] = $userdetails['first_name'];
            $userData['last_name'] = $userdetails['last_name'];
            $userData['email'] = $userdetails['email'];
            $userData['address'] = $userdetails['address1'];
            $userData['state'] = $userdetails['state'];
            $userData['zip'] = $userdetails['postcode'];
            $userData['country'] = $userdetails['country'];
            $userData['customerInvoiceRef'] = $reservationPostdata->id;

            // gather the card details
            $ccArray['x_card_num'] = $x_card_num;
            //$ccArray['x_exp_date'] = date("d",$cc_expire_date_month).date("y",$cc_expire_date_year);
            $ccArray['x_exp_date_month'] = date("m", mktime(0, 0, 0, $cc_expire_date_month, 1, $cc_expire_date_year));
            $ccArray['x_exp_date_year'] = date("y", mktime(0, 0, 0, 1, 1, $cc_expire_date_year));
            $ccArray['x_amount'] = $chargetotal*100;// price in cents
            $ccArray['x_description'] = $description;
            $ccArray['x_card_code'] = $x_card_code;

            $AuthObj = new RM_Plugin_eWAYpayments();
            $response = $AuthObj->Process($bookingref, $ccArray, $userData);

            RM_Log::toLog("eWay Payments: Processed Card");

            if ($response['EWAYTRXNSTATUS'] === "True") {
                // this is the return if the transaction passed
                $return = array(
                    "success" => true,
                    "authcode" => $response["EWAYAUTHCODE"],
                    "transid" => $response["EWAYTRXNNUMBER"],
                    "bookingref" => $response["EWAYTRXNREFERENCE"],
                    "amountcharged" => $response["EWAYRETURNAMOUNT"],
                    "transtype" => $response["TransactionType"],
                    "msg" => $description,
                    "responsecode" => $response["EWAYTRXNERROR"]
                );

                // save the reservation
                RM_Log::toLog("eWay Payments: Payment Completed Successfully for booking ref: " . $bookingref);

                $model = new RM_Reservations();
                $reservation = $model->find($bookingref)->current();
                RM_Log::toLog("eWay Payments: Reservation Record ID: " . $reservation->id);

                $model->confirm($reservation);
                RM_Log::toLog("eWay Payments: Confirmed Updated");

                $model->inProgressComplete($reservation);
                RM_Log::toLog("eWay Payments: InProgress Marker Updated");

                $total_paid = $return["amountcharged"] / 100; // price back to major
                RM_Log::toLog("eWay Payments: Total Passed back from eWAY Payments: " . $total_paid);

                $billingModel = new RM_Billing();
                $billingRow = $billingModel->createRow();
                $billingRow->reservation_id = $bookingref;
                $billingRow->total_paid = $total_paid;
                $billingID = $billingRow->save();
                RM_Log::toLog("eWay Payments: Billing Updated");

                // save the payment information
                $billingPaymentsModel = new RM_BillingPayments();
                $billingPaymentRow = $billingPaymentsModel->createRow();
                $billingPaymentRow->id = $billingID;
                $billingPaymentRow->provider = "eway.com.au";
                $billingPaymentRow->transaction_id = $return["bookingref"];
                $billingPaymentRow->status = "success";
                $billingPaymentRow->total = $total_paid;
                $billingPaymentRow->transaction_date = Date("Y-m-d");
                $billingPaymentRow->save();

                RM_Notifications_Manager::getInstance()->fire('eWAYpaymentsComplete', $reservation);

                RM_Log::toLog("eWay Payments: Billing Payments Completed");
            } else {
                // this is the return if the transaction failed at Authorize.net

                if ($response["EWAYRETURNAMOUNT"] !== null){
                    $amountCharged = $response["EWAYRETURNAMOUNT"];
                } else {
                    $amountCharged = "0.00";
                }

                $return = array(
                    "success" => false,
                    "authcode" => $response["EWAYAUTHCODE"],
                    "transid" => $response["EWAYTRXNNUMBER"],
                    "bookingref" => $bookingref,
                    "amountcharged" => $amountCharged,
                    "transtype" => $response["TransactionType"],
                    "msg" => $this->_translate->_('User.eWAYpayments.Main', 'FailedMsg'),
                    "responsecode" => $response["EWAYTRXNERROR"]
                );
            }
        } else {
            // this is the return if the card number is not valid
            $return = array(
                "success" => false,
                "authcode" => 0,
                "transid" => 0,
                "bookingref" => 0,
                "amountcharged" => 0,
                "transtype" => 0,
                "msg" => $this->_translate->_('User.eWAYpayments.Main', 'CardNumberNotValid'),
                "responsecode" => 0
            );
        }

        RM_Log::toLog("*** eWay Payments: Controller processJsonAction Ended ***");
        return array(
            'data' => $return
        );
    }

    public function ccFormAction() {

    }

    public function cancelAction() {
        //We need to reset user object accorting to ticket #59 in Trac
        RM_Reservation_Manager::getInstance()->resetUser();

        // return a cancelled message
        return array(
            'data' => array('success' => true)
        );
    }

    public function successAction() {

        RM_Reservation_Manager::getInstance()->setPaymentStatus(RM_Payments_Status::TRANSACTION_END_SUCCESSFULLY);
        $this->_forward('success', 'Payments');
    }

}